/**
 * Created by Weizehua on 2017/1/21.
 */

import * as request from "request-promise"
import {Options} from "request-promise"
import {NeteaseChecksum} from "./NeteaseChecksum";
import {Singleton} from "ts.di";

@Singleton()
export class NeteaseSMS {
    constructor(private appKey: string, private appSecret: string){}
    async requestSendCaptcha(phone: string, deviceId?: string, templateId?: number,
                       captchaLength?: number) {
        let nonce = NeteaseChecksum.generateNonce(128);
        let date = new Date();
        let options: Options = {
            method:'POST',
            url: this.sendCaptchaRequestUrl,
            headers : {
                AppKey: this.appKey,
                Nonce: nonce,
                CurTime: date,
                CheckSum: await NeteaseChecksum.generate(this.appSecret, date, nonce),
                'Content-Type':'application/x-www-form-urlencoded;charset=utf-8;',
            },
            form:{
                mobile: phone,
                deviceId: deviceId,
                templateId: templateId,
                codeLen: captchaLength
            }
        };
        let res = JSON.parse(await request(options));
        if(res.code === 200)
            return res.obj;
        throw new Error(`NeteaseSMS.sendcode return : ${res}`);
    }

    private sendCaptchaRequestUrl:string = "https://api.netease.im/sms/sendcode.action";
    // checkCaptchaRequestUrl:string = "https://api.netease.im/sms/sendcode.action";
}
